<?php
namespace frontend\controllers;

use common\pay\wxpay\core\JsApiPay;
use frontend\ext\MyWxPayNotify;
use frontend\models\Order;
use frontend\models\OrderCoupon;
use frontend\models\User;
use frontend\models\UserCoupon;
use Yii;
use yii\base\Exception;
use yii\helpers\Url;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/3
 * Time: 16:14
 */
class NotifyController extends \common\controllers\BaseController
{
    public $enableCsrfValidation = false;
//
//    /**
//     * 返回JSON
//     * @param int $status
//     * @param string $message
//     * @param array $data
//     * @param bool|true $is_do_walk
//     * @return mixed
//     */
//    public function showResult($status = 200, $message = '', $data = [], $is_do_walk = true)
//    {
//        $result = [
//            'status' => strval($status),
//            'message' => $message,
//            'data' => $data
//        ];
//        return str_replace('":null', '":""', json_encode($result));
//    }


    /**
     *微信支付回调
     */
    public function actionWxnotify()
    {
        \Yii::info('start', 'orders');
        $notify = new MyWxPayNotify();
        $notify->Handle(false);
    }

    /**
     * 优惠券恢复
     * 超过支付时间未支付的订单，所绑定的优惠券，解除绑定
     */
    public function actionCouponRestore()
    {
        $timeout_seconds = 30 * 60;
        $orders = Order::find()
            ->leftJoin('order_coupon', 'order_coupon.o_order_id = order.id')
            ->where(['order.is_paid' => 0, 'order.is_waitting_callback' => 0])
            ->andWhere(['<', 'order_coupon.create_time', time() - $timeout_seconds])
            ->all();
        $result_msg = empty($orders) ? '无可操作订单' : '';
        foreach ($orders as $order) {
            $tran = Yii::$app->db->beginTransaction();
            try {
                $order->price_discount_coupon = 0;
                $order->price_payable = $order->price_all - $order->price_all;
                if (!$order->save()) {
                    throw new Exception('订单保存异常！订单ID：' . $order->id);
                }
                $order_coupon = OrderCoupon::find()->where(['o_order_id' => $order->id])->one();
                $coupon = UserCoupon::find()
                    ->where(['id' => $order_coupon->o_coupon_id])
                    ->one();
                if ($coupon->can_use_times != 0) {
                    $coupon->used_times = $coupon->used_times - 1;
                    if (!$coupon->save()) {
                        throw new Exception('优惠券操作异常！订单ID：' . $coupon->id);
                    }
                }
                $order_coupon->delete();
                $tran->commit();
            } catch (Exception $e) {
                $tran->rollBack();
                $result_msg .= $e->getMessage();
                \Yii::info($e->getMessage(), 'coupon_restore');
            }
        }
        \Yii::info($result_msg, 'coupon_restore');
        echo $result_msg;
        exit;
    }


}